<template >
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 点击首页会跳转到home -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click=" dialogVisible=true">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 渲染获得的用户数据列表 -->
      <el-table :data="usersList" border stripe class="table">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="role_name" label="角色名"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>

        <!-- 作用域插槽，V-slot中的scope.mg_state会覆盖prop="mg_state"，所以可以删掉prop -->
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 作用域插槽，操作栏 -->
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="修改" placement="top">
              <el-button
                @click="dialogEdit(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button
                type="primary"
                icon="el-icon-s-tools"
                size="mini"
                @click="addSelectRole(scope.row)"
              ></el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button
                type="primary"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUsers(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- Dialog添加用户对话框 -->

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      dialogVisible="true"
      @close="addUserClose"
    >
      <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="100px">
        <!-- 用户添加信息表单 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- Dialog修改用户对话框 -->

    <el-dialog title="修改用户" :visible.sync="dialogVisibleEdit" width="50%">
      <el-form :model="editForm" :rules="editRules" ref="editRef" label-width="100px">
        <!-- 用户修改信息表单 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addSelectRoleDialogVisible"
      width="50%"
      @close="resetAddRoleDialogVisible"
    >
      <p>当前的用户：{{roleInfo.username}}</p>
      <p>当前的角色：{{roleInfo.role_name}}</p>
      <el-select v-model="selectRoleId" placeholder="请选择">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click=" addSelectRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click=" addUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱
    var checkEmail = (rule, value, callback) => {
      var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (reg.test(value)) {
        return callback();
      } else {
        callback(new Error("邮箱格式不正确"));
      }
    };
    //验证手机
    var checkMobile = (rule, value, callback) => {
      var reg = /^1\d{10}$/;
      if (reg.test(value)) {
        return callback();
      } else {
        callback(new Error("手机格式不正确"));
      }
    };
    return {
      usersList: [],
      roleInfo: {},
      roleList: [],
      //下拉角色菜单双向绑定数据
      selectRoleId: "",
      total: 0,
      queryInfo: { query: "", pagenum: 1, pagesize: 2 },
      dialogVisible: false,
      dialogVisibleEdit: false,
      addSelectRoleDialogVisible: false,
      //把从数据库获得的信息存放起来，必须是对象
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //存放根据ID从数据库动态获取的数据，必须是对象
      editForm: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" } //验证邮箱
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" } //验证手机
        ]
      },
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" } //验证邮箱
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" } //验证手机
        ]
      }
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    //获取用户列表
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      console.log(res);

      if (res.meta.status !== 200) {
        this.$message.error("获取列表失败");
      } else {
        this.usersList = res.data.users;
        this.total = res.data.total;
      }
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUsersList();
    },
    //监听页码改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    //监听状态
    async stateChange(newState) {
      console.log(newState);
      const { data: res } = await this.$http.put(
        `users/${newState.id}/state/${newState.mg_state}`
      );
      if (res.meta.status !== 200) {
        newState.mg_state = !newState.mg_state;
        return this.$message.error("更新状态失败");
      } else {
        return this.$message.success("更新状态成功");
      }
    },
    //关闭Dialog对话框后重置
    addUserClose() {
      this.$refs.ruleForm.resetFields();
    },
    //先进行预验证，如果为true，则调用API接口
    addUser() {
      this.$refs.ruleForm.validate(async validate => {
        if (!validate) {
          return;
        } else {
          const { data: res } = await this.$http.post("users", this.addForm); //addForm是data里面的
          if (res.meta.status !== 201) {
            return this.$message.error("添加失败");
          } else {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.getUsersList();
          }
        }
      });
    },
    //修改用户前获得/查询用户信息，然后把查询到的数据信息传到data（）中的editForm中
    async dialogEdit(id) {
      this.dialogVisibleEdit = true;
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        this.$message.error("查询用户失败");
      } else {
        this.editForm = res.data;
      }
    },
    //预验证修改用户信息规则，没有问题则发起请求
    editUser() {
      this.$refs.editRef.validate(async validate => {
        if (!validate) {
          return;
        } else {
          //发起修改用户数据的请求
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            }
          );
          if (res.meta.status !== 200) {
            return this.$message.error("更改失败");
          } else {
            //关闭对话框
            this.dialogVisibleEdit = false;
            //刷新数据列表
            this.getUsersList();
            //提示更改成功
            this.$message.success("更改成功");
          }
        }
      });
    },
    //删除用户
    async deleteUsers(id) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (result !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除"
        });
      } else {
        const { data: res } = await this.$http.delete("users/" + id);
        if (res.meta.status !== 200) {
          return this.$message({
            type: "info",
            message: "已取消删除"
          });
        } else {
          this.getUsersList();
        }
      }
    },
    //分配角色窗口
    async addSelectRole(role) {
      this.roleInfo = role;

      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return;
      } else {
        this.roleList = res.data;
        this.addSelectRoleDialogVisible = true;
      }
    },
    //点击确定后给当前用户添加角色
    async addUserRole() {
      if (!this.selectRoleId) {
        return this.$message.error("请选择用户角色");
      } else {
        const { data: res } = await this.$http.put(
          `users/${this.roleInfo.id}/role`,
          {
            rid: this.selectRoleId
          }
        );
        if (res.meta.status !== 200) {
          return;
        } else {
          this.$message.success("添加角色成功");
          this.getUsersList();
          this.addSelectRoleDialogVisible = false;
        }
      }
    },
    //用户角色窗口关闭后重置
    resetAddRoleDialogVisible() {
      this.roleInfo = {};
      this.selectRoleId = "";
    }
  }
};
</script>

<style lang="less" scoped>
body .el-table th.gutter {
  display: table-cell !important;
}
</style>